export const audioRegex = /<p[^>]*class=('|")?audio\1[^>]*>(.*?)<\/p>/g;
// export const audioRegex = /<audio[^>]*>.*?<\/audio>/g
// 处理音频资源
export const extractedAudio = (obj: any[]) => {
  if (Array.isArray(obj) && obj.every((item) => typeof item === "string")) {
    return obj;
  }
  return obj.map((item: { [s: string]: unknown } | ArrayLike<unknown>) => {
    const extractedAudioTags: any = {};
    Object.entries(item).forEach(([key, value]) => {
      if (Array.isArray(value)) {
        // 如果value是数组，则递归调用handleData函数
        extractedAudioTags[key] = extractedAudio(value);
      } else if (typeof value === "string" && value.startsWith("<")) {
        const audioSrc = getAudioSrcFromString(value);
        if (audioSrc) {
          extractedAudioTags[key + "Src"] = audioSrc;
          // 否则，直接将value赋值给extractedAudioTags
          extractedAudioTags[key] = value
            .replace(/\n/g, "")
            .replace(audioRegex, "");
        } else {
          extractedAudioTags[key] = value;
        }
      } else if (typeof value === "string" && value.startsWith("[")) {
        try {
          // 如果value是JSON字符串，parse后进行解析
          const jsonValue = JSON.parse(value);
          if (jsonValue.every((jV: unknown) => typeof jV === "string")) {
            const arr: string[] = [];
            const arrSrc: (string | null)[] = [];
            // 如果value是字符串数组，则直接赋值
            jsonValue.forEach((jV: string) => {
              const audioSrc = getAudioSrcFromString(jV);
              if (audioSrc) {
                arrSrc.push(audioSrc);
                arr.push(jV.replace(/\n/g, "").replace(audioRegex, ""));
              } else {
                arr.push(jV);
              }
            });
            if (arrSrc.length > 0) {
              extractedAudioTags[key + "Src"] = JSON.stringify(arrSrc);
            }
            extractedAudioTags[key] = JSON.stringify(arr);
          } else {
            extractedAudioTags[key] = JSON.stringify(extractedAudio(jsonValue));
          }
        } catch (error) {
          console.warn(error);
          extractedAudioTags[key] = value;
        }
      } else {
        extractedAudioTags[key] = value;
      }
    });

    return extractedAudioTags;
  });
};

export const extractedAudioSrc = (text: string) => {
  let newText = "";
  const audioSrc = getAudioSrcFromString(text);
  if (audioSrc) {
    // 否则，直接将value赋值给extractedAudioTags
    newText = text.replace(/\n/g, "").replace(audioRegex, "");
  } else {
    newText = text;
  }
  return {
    text: newText,
    src: audioSrc,
  };
};

export const getAudioSrcFromString = (htmlString: string) => {
  const regex = /<audio.*?src="([^"]*)"[^>]*>/gi;
  const match = regex.exec(htmlString);
  if (match && match[1]) {
    return match[1]; // 返回找到的src属性值
  }
  return ""; // 如果没有找到，返回null
};
